package com.example.lots_of_demo.filter;

import com.example.lots_of_demo.utils.JWTUtils;
import com.example.lots_of_demo.utils.ReleasePassUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author : LZJ
 * @description : code for LZJ
 * @date : 2021/2/13
 */
@Slf4j
public class JwtAuthenticationTokenFilter implements Filter {

    @Value("${jwt.tokenKeyName}")
    private String tokenKeyName;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JWTUtils jwtUtils;
    @Autowired
    private ReleasePassUtils releasePassUtils;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        if(!releasePassUtils.isIncludeReleasePassList(request.getRequestURI())) {
            String authHeader = null;
            try {
                authHeader = request.getHeader(tokenKeyName);
            } catch (NullPointerException e) {

            }
            if (authHeader != null && authHeader.startsWith(tokenHead)) {
                // The part after "Bearer "
                String authToken = authHeader.substring(tokenHead.length());
                String username = jwtUtils.getUserNameFromToken(authToken);
                if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                    UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                    if (jwtUtils.validateToken(authToken, userDetails)) {
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        log.info("用户<<{}>>,访问<<{}>>,通过token验证", username, request.getRequestURI());
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                }
            }
        }
        filterChain.doFilter(request, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
